GOAL¶

Build a simulated decision-making engine that evaluates real-time stock data and outputs decision making in layman's terms

In [11]:
## Installing required package
!pip install yfinance plotly pandas --quiet
pip install yahoo_fin
In [64]:
pip install pandoc
Collecting pandoc
  Downloading pandoc-2.4.tar.gz (34 kB)
  Preparing metadata (setup.py) ... done
Collecting plumbum (from pandoc)
  Downloading plumbum-1.9.0-py3-none-any.whl.metadata (10 kB)
Requirement already satisfied: ply in /opt/anaconda3/lib/python3.12/site-packages (from pandoc) (3.11)
Downloading plumbum-1.9.0-py3-none-any.whl (127 kB)
Building wheels for collected packages: pandoc
  Building wheel for pandoc (setup.py) ... done
  Created wheel for pandoc: filename=pandoc-2.4-py3-none-any.whl size=34792 sha256=b3188059e9e47683c19d9c5eeb5df7feb8debfcc508717ae4601221cb3a0d5d9
  Stored in directory: /Users/sushmita/Library/Caches/pip/wheels/9c/2f/9f/b1aac8c3e74b4ee327dc8c6eac5128996f9eadf586e2c0ba67
Successfully built pandoc
Installing collected packages: plumbum, pandoc
Successfully installed pandoc-2.4 plumbum-1.9.0
Note: you may need to restart the kernel to use updated packages.
In [ ]:
 

Calculate simple decision and plot stock trends¶

In [13]:
# 📌 Imports
import yfinance as yf
import pandas as pd
import plotly.graph_objs as go
from IPython.display import display, Markdown

# 📌 Input Tickers
tickers = ['AAPL', 'MSFT', 'NVDA', 'TSLA']  # You can change this list

# 📌 Fetch and Analyze
def analyze_stock(ticker):
    stock = yf.Ticker(ticker)
    df = stock.history(period="5d", interval="1h")

    # Decision Logic
    latest_close = df['Close'].iloc[-1]
    previous_close = df['Close'].iloc[-2]
    pct_change = (latest_close - previous_close) / previous_close * 100

    if pct_change < -3:
        decision = f"🟢 BUY (Dropped {pct_change:.2f}%)"
    elif pct_change > 3:
        decision = f"🔴 SELL (Rose {pct_change:.2f}%)"
    else:
        decision = f"⚪ HOLD (Stable {pct_change:.2f}%)"
    
    return df, decision, latest_close

# 📌 Plot and Show Results
for ticker in tickers:
    df, decision, price = analyze_stock(ticker)

    display(Markdown(f"### {ticker} — ${price:.2f} — {decision}"))

    # Line chart using Plotly
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=df.index, y=df['Close'], mode='lines', name='Close Price'))
    fig.update_layout(title=f"{ticker} Stock Price (5d | 1h interval)", xaxis_title='Date', yaxis_title='Price ($)')
    fig.show()

AAPL — $210.06 — ⚪ HOLD (Stable -0.44%)¶

MSFT — $511.85 — ⚪ HOLD (Stable -0.05%)¶

NVDA — $173.11 — ⚪ HOLD (Stable -0.10%)¶

TSLA — $319.37 — ⚪ HOLD (Stable 0.14%)¶

Can you simulate bloomberg data factors which help in decision making¶

In [16]:
import yfinance as yf
import pandas as pd
from IPython.display import display, Markdown

# 📌 Tickers to Analyze
tickers = ['AAPL', 'MSFT', 'NVDA']

def simulate_bloomberg_metrics(ticker):
    stock = yf.Ticker(ticker)
    info = stock.info
    hist = stock.history(period="6mo")

    # ✅ Key Bloomberg-style metrics
    pe = info.get('trailingPE', None)
    peg = info.get('pegRatio', None)
    rev_growth = info.get('revenueGrowth', None)
    profit_margin = info.get('profitMargins', None)
    beta = info.get('beta', None)
    dividend_yield = info.get('dividendYield', None)
    
    # 📈 Technical Indicators
    hist['SMA_50'] = hist['Close'].rolling(window=50).mean()
    hist['SMA_200'] = hist['Close'].rolling(window=200).mean()

    current_price = hist['Close'].iloc[-1]
    sma50 = hist['SMA_50'].iloc[-1]
    sma200 = hist['SMA_200'].iloc[-1]

    # 📊 Simulated Decision Logic (basic rules)
    decision = []
    if pe and pe < 20:
        decision.append("Valuation Attractive (PE < 20)")
    if peg and peg < 1:
        decision.append("High Growth Potential (PEG < 1)")
    if profit_margin and profit_margin > 0.2:
        decision.append("Strong Profitability (PM > 20%)")
    if rev_growth and rev_growth > 0.1:
        decision.append("Strong Revenue Growth (>10%)")
    if sma50 > sma200:
        decision.append("Positive Momentum (SMA 50 > 200)")

    final_decision = "BUY" if len(decision) >= 3 else ("HOLD" if len(decision) == 2 else "SELL")

    display(Markdown(f"### {ticker} — Current Price: ${current_price:.2f} — **{final_decision}**"))
    for d in decision:
        display(Markdown(f"- ✅ {d}"))
    if not decision:
        display(Markdown("- ⚠️ No strong buy indicators"))

# 🔁 Run for all tickers
for ticker in tickers:
    simulate_bloomberg_metrics(ticker)

AAPL — Current Price: $210.02 — SELL¶

  • ✅ Strong Profitability (PM > 20%)

MSFT — Current Price: $511.70 — HOLD¶

  • ✅ Strong Profitability (PM > 20%)
  • ✅ Strong Revenue Growth (>10%)

NVDA — Current Price: $173.00 — HOLD¶

  • ✅ Strong Profitability (PM > 20%)
  • ✅ Strong Revenue Growth (>10%)
In [ ]:
 
In [19]:
import pandas as pd

# NASDAQ Listed Stocks
nasdaq_url = "ftp://ftp.nasdaqtrader.com/SymbolDirectory/nasdaqlisted.txt"
nasdaq = pd.read_csv(nasdaq_url, sep='|')
nasdaq_tickers = nasdaq['Symbol'].tolist()[:-1]  # Remove last row (footer)

# NYSE/AMEX Stocks
other_url = "ftp://ftp.nasdaqtrader.com/SymbolDirectory/otherlisted.txt"
other = pd.read_csv(other_url, sep='|')
other_tickers = other['ACT Symbol'].tolist()[:-1]

# Combine
all_us_tickers = list(set(nasdaq_tickers + other_tickers))
print(f"Total US Tickers: {len(all_us_tickers)}")
Total US Tickers: 11577
In [ ]:
 
In [30]:
import yfinance as yf
import pandas as pd
from IPython.display import display, Markdown

# Sample Subset of US tickers for demo (replace with full list later)
sample_tickers = [ 'AAPL', 'MSFT' ]

buy_stocks = []

def evaluate_buy_candidate(ticker):
    try:
        stock = yf.Ticker(ticker)
        info = stock.info
        price = info.get('currentPrice', 0)
        peg = info.get('pegRatio', None)
        rev_growth = info.get('revenueGrowth', None)
        profit_margin = info.get('profitMargins', None)

        # Fetch historical data for trend
        df = stock.history(period="6mo")
        df['SMA50'] = df['Close'].rolling(window=50).mean()
        df['SMA200'] = df['Close'].rolling(window=200).mean()

        if len(df) < 200:
            return  # not enough data

        sma50 = df['SMA50'].iloc[-1]
        sma200 = df['SMA200'].iloc[-1]

        # ✅ Buy Signal Conditions
        if price < 5 and peg and peg < 1.5 and rev_growth and rev_growth > 0.05 and sma50 > sma200:
            buy_stocks.append({
                'Ticker': ticker,
                'Price': price,
                'PEG': peg,
                'Rev Growth': rev_growth,
                'Profit Margin': profit_margin,
                'SMA50>SMA200': True
            })
    except:
        pass

# Run evaluation
for ticker in sample_tickers:
    evaluate_buy_candidate(ticker)

# Show Results
buy_df = pd.DataFrame(buy_stocks)
if not buy_df.empty:
    display(Markdown("### 🟢 **Buy Signal for Stocks Under $5**"))
    display(buy_df)
else:
    display(Markdown("### ⚠️ No Buy Signals Found in Sample List"))

⚠️ No Buy Signals Found in Sample List¶

In [51]:
## HOW DOES STOCKS IN NASDAQ COMPARE TO S&P500
In [53]:
## Full Market Scan
In [55]:
import pandas as pd

# Get NASDAQ tickers
nasdaq_url = "ftp://ftp.nasdaqtrader.com/SymbolDirectory/nasdaqlisted.txt"
nasdaq = pd.read_csv(nasdaq_url, sep='|')
nasdaq_tickers = nasdaq['Symbol'].tolist()[:-1]  # Remove footer

# Get NYSE/Other tickers
other_url = "ftp://ftp.nasdaqtrader.com/SymbolDirectory/otherlisted.txt"
other = pd.read_csv(other_url, sep='|')
other_tickers = other['ACT Symbol'].tolist()[:-1]

# Combine
all_tickers = list(set(nasdaq_tickers + other_tickers))
print(f"✅ Total US Tickers: {len(all_tickers)}")
✅ Total US Tickers: 11577
In [ ]: